var contacts = new Array();

var buddyHighlightColor, buddyHighlightTextColor, buddyHighlightIdleTextColor;
var purplePath;
var sizeType, sizeStaticBuddies;
var yMousePos, scrollTimer, scrollPos;
var xmlLastModified;

function init(){
	System.Gadget.settingsUI = 'settings.html';
	System.Gadget.onSettingsClosed = settingsClosed;
	readSettings();
	shadowGadget();
	document.getElementById('title').innerHTML = System.Gadget.name + ' v' + System.Gadget.version;
	xmlLastModified = new Date(0);
	setInterval('checkForUpdates()', 1000);
}

function checkForUpdates(){
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	var mtime = new Date(fso.GetFile(purplePath + "\\pidglet.xml").DateLastModified);
	if(mtime > xmlLastModified){
		xmlLastModified = mtime;
		updateList();
	}
}

function updateList(){
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async = false;
	xmlDoc.load(purplePath + "\\pidglet.xml");
	var buddies = xmlDoc.getElementsByTagName('Buddy');
	
	//add new buddies and update existing ones
	for(var i = 0; i < buddies.length; i++){
		if(!buddyExists(buddies[i].attributes[0].value)){
			addBuddy(buddies[i].text, buddies[i].attributes[0].value, buddies[i].attributes[1].value, buddies[i].attributes[2].value);
		} else {
			checkBuddyStatus(buddies[i].text, buddies[i].attributes[0].value, buddies[i].attributes[1].value, buddies[i].attributes[2].value);
		}
	}
	
	//remove missing buddies
	var synced = false;
	while(!synced){
		synced = syncMissingBuddies(buddies);
	}
	
	document.getElementById('footer').innerHTML = '(' + contacts.length + ' online)';
	
	colorizeBuddies();
	resizeGadget();
}

function syncMissingBuddies(buddies){
	synced = true;
	for(var i = 0; i < contacts.length; i++){
		if(buddyGone(buddies, i)){
			synced = false;
			remBuddy(i);
			break;
		}
	}
	return synced;
}

function getIdleTime(idle){
	var idleTime = '';
	if(idle != 0){
		idleTime = 'Idle';
		if(idle > 0){
			var hours = Math.floor(idle / 3600);
			var mins = Math.round((idle % 3600) / 60);
			idleTime += ': ' + hours + 'h' + ' ' + mins + 'm';
		}
	}
	return idleTime;
}

function checkBuddyStatus(name, id, status, idle){
	for(var i = 0; i < contacts.length; i++){
		if(contacts[i].altText == id){
			if(!endsWith(contacts[i].firstChild.src, getStatusImg(status)) || contacts[i].title != getIdleTime(idle)){
				contacts[i].innerHTML = '<img alt="' + status + '" src="' + getStatusImg(status) + '" /> ' + name;
				if(idle != 0){
					if(!endsWith(contacts[i].className, 'Idle')){
						contacts[i].className += 'Idle';
					}
					contacts[i].title = getIdleTime(idle);
				} else {
					if(endsWith(contacts[i].className, 'Idle')){
						contacts[i].className = contacts[i].className.substr(0, contacts[i].className.length - 4);
					}
					contacts[i].title = '';
				}
			}
		}
	}
	return false;
}

function endsWith(testString, endingString){
      if(endingString.length > testString.length) return false;
      return testString.indexOf(endingString)==(testString.length-endingString.length);
}

function buddyExists(id){
	for(var i = 0; i < contacts.length; i++){
		if(contacts[i].altText == id){
			return true;
		}
	}
	return false;
}

function buddyGone(buddies, which){
	var gone = true;
	for(var i = 0; i < buddies.length; i++){
		if(buddies[i].attributes[0].value == contacts[which].altText){
			gone = false;
		}
	}
	return gone;
}

function getStatusImg(status){
	var imgname = 'busy.png';
	if(status == 'Away'){
		imgname = 'away.png';
	} else if(status == 'Available'){
		imgname = 'available.png';
	} else if(status == 'Extended away'){
		imgname = 'extended-away.png';
	} else if(status == 'Invisible'){
		imgname = 'invisible.png';
	}
	return 'images/status/' + imgname;
}

function addBuddy(name, id, status, idle){
	var buddy = document.createElement('div');
	buddy.title = '';
	buddy.className = '';
	if(idle != 0){
		buddy.title = getIdleTime(idle);
		buddy.className = 'Idle';
	}
	buddy.innerHTML = '<img alt="' + status + '" src="' + getStatusImg(status) + '" /> ' + name;
	buddy.altText = id;
	buddy.onmouseover = function(){ this.style.backgroundColor = buddyHighlightColor; this.style.color = endsWith(this.className, 'Idle') ? buddyHighlightIdleTextColor : buddyHighlightTextColor; };
	buddy.onmouseout = function(){ this.style.backgroundColor = ''; this.style.color = ''; };
	buddy.onclick = function(){ openChat(this.altText); };
	contacts.push(buddy);
	contacts = contacts.sort(sortBuddies);
	//find the new contact's position in the user list, and insert the div at the correct location
	for(var i = 0; i < contacts.length; i++){
		if(buddy == contacts[i]){
			if(i == contacts.length - 1){
				document.getElementById('buddycontainer').appendChild(buddy);
			} else {
				document.getElementById('buddycontainer').insertBefore(buddy, contacts[i + 1]);
			}
			break;
		}
	}
}

function remBuddy(which){
	document.getElementById('buddycontainer').removeChild(contacts[which]);
	contacts.splice(which, 1);
}

function colorizeBuddies(){
	for(var i = 0; i < contacts.length; i++){
		var idlestr = '';
		if(endsWith(contacts[i].className, 'Idle')) { // if there is an idle time in the last div
			idlestr = 'Idle';
		}
		if(i % 2 == 0){
			contacts[i].className = 'buddy' + idlestr;
		} else {
			contacts[i].className = 'buddyalt' + idlestr;
		}
	}
}

function resizeGadget(){
	if(sizeType == 0){
		var listsize = contacts.length * 18;
		if(listsize < 18){
			listsize = 18;
		}
		document.getElementById('userlist').style.height = listsize + 'px';
		document.body.style.height = (45 + listsize) + 'px';
		shadowGadget();
	}
}

function shadowGadget(){
	var bg = document.getElementById('background');
	bg.removeObjects();
	bg.addImageObject('url(images/shadow_top.png)', 0, 0);
	bg.addImageObject('url(images/shadow_sides.png)', 0, 4);
	var listsize;
	if(sizeType == 0){
		listsize = contacts.length;
	} else {
		listsize = sizeStaticBuddies;
	}
	if(listsize > 0){
		for(var i = 0; i < listsize; i++){
			bg.addImageObject('url(images/shadow_sides.png)', 0, (i + 1) * 18 + 4);
		}
		bg.addImageObject('url(images/shadow_sides.png)', 0, listsize * 18 + 22);
		bg.addImageObject('url(images/shadow_bottom.png)', 0, listsize * 18 + 40);
	} else {
		bg.addImageObject('url(images/shadow_sides.png)', 0, 22);
		bg.addImageObject('url(images/shadow_sides.png)', 0, 40);
		bg.addImageObject('url(images/shadow_bottom.png)', 0, 58);
	}
}

function sortBuddies(a, b){
	if(a.innerText.toLowerCase() > b.innerText.toLowerCase()){
		return 1;
	} else if(a.innerText.toLowerCase() < b.innerText.toLowerCase()) {
		return -1;
	}
	return 0;
}

function openChat(name){
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	var cmd = fso.CreateTextFile(purplePath + "\\pidglet-cmd", true);
	cmd.WriteLine(name);
	cmd.Close();
}

function settingsClosed(event){
	if(event.closeAction == event.Action.commit){
		readSettings();
	}
}

function readSettings(){
	var titleColor = System.Gadget.Settings.readString('TitleColor');
	var titleTextColor = System.Gadget.Settings.readString('TitleTextColor');
	var buddyColor = System.Gadget.Settings.readString('BuddyColor');
	var buddyAltColor = System.Gadget.Settings.readString('BuddyAltColor');
	var buddyTextColor = System.Gadget.Settings.readString('BuddyTextColor');
	var buddyIdleTextColor = System.Gadget.Settings.readString('BuddyIdleTextColor');
	buddyHighlightColor = System.Gadget.Settings.readString('BuddyHighlightColor');
	buddyHighlightTextColor = System.Gadget.Settings.readString('BuddyHighlightTextColor');
	buddyHighlightIdleTextColor = System.Gadget.Settings.readString('BuddyHighlightIdleTextColor');
	
	if(titleColor == ''){ titleColor = '#11131D'; System.Gadget.Settings.writeString('TitleColor', titleColor); }
	if(titleTextColor == ''){ titleTextColor = '#8888AA'; System.Gadget.Settings.writeString('TitleTextColor', titleTextColor); }
	if(buddyColor == ''){ buddyColor = '#21293A'; System.Gadget.Settings.writeString('BuddyColor', buddyColor); }
	if(buddyAltColor == ''){ buddyAltColor = '#151A27'; System.Gadget.Settings.writeString('BuddyAltColor', buddyAltColor); }
	if(buddyTextColor == ''){ buddyTextColor = '#FFFFFF'; System.Gadget.Settings.writeString('BuddyTextColor', buddyTextColor); }
	if(buddyIdleTextColor == ''){ buddyIdleTextColor = '#666699'; System.Gadget.Settings.writeString('BuddyIdleTextColor', buddyIdleTextColor); }
	
	if(buddyHighlightColor == ''){ buddyHighlightColor = '#31397A'; System.Gadget.Settings.writeString('BuddyHighlightColor', buddyHighlightColor); }
	if(buddyHighlightTextColor == ''){ buddyHighlightTextColor = '#FFFFFF'; System.Gadget.Settings.writeString('BuddyHighlightTextColor', buddyHighlightTextColor); }
	if(buddyHighlightIdleTextColor == ''){buddyHighlightIdleTextColor = '#000033'; System.Gadget.Settings.writeString('BuddyHighlightIdleTextColor', buddyHighlightIdleTextColor); }
	
	updateCSS('#title', false, titleColor);
	updateCSS('#userlist', false, titleColor);
	updateCSS('#footer', false, titleColor);
	updateCSS('#title', true, titleTextColor);
	updateCSS('#footer', true, titleTextColor);
	updateCSS('#footer a', true, titleTextColor);
	
	updateCSS('.buddy', false, buddyColor);
	updateCSS('.buddyalt', false, buddyAltColor);
	updateCSS('#userlist', true, buddyTextColor);
	
	updateCSS('.buddyidle', false, buddyColor);
	updateCSS('.buddyidle', true, buddyIdleTextColor);
	updateCSS('.buddyaltidle', false, buddyAltColor);
	updateCSS('.buddyaltidle', true, buddyIdleTextColor);
	
	sizeType = parseInt(System.Gadget.Settings.read('SizeType'));
	if(isNaN(sizeType) || sizeType < 0 || sizeType > 1){ sizeType = 0; System.Gadget.Settings.write('SizeType', 0); }
	sizeStaticBuddies = parseInt(System.Gadget.Settings.read('SizeStaticBuddies'));
	if(isNaN(sizeStaticBuddies) || sizeStaticBuddies < 1){ sizeStaticBuddies = 4; System.Gadget.Settings.write('SizeStaticBuddies', sizeStaticBuddies); }
	
	if(sizeType == 0){
		document.onmousemove = null;
		document.getElementById('userlist').onmouseover = null;
		document.getElementById('userlist').onmouseout = null;
		document.getElementById('buddycontainer').style.top = '';
		resizeGadget();
	} else {
		var listsize = sizeStaticBuddies * 18;
		document.getElementById('userlist').style.height = listsize + 'px';
		document.body.style.height = (45 + listsize) + 'px';
		scrollPos = 0;
		document.getElementById('buddycontainer').style.top = '';
		document.onmousemove = getMousePosition;
		document.getElementById('userlist').onmouseover = function(){ scrollBuddies(true); }
		document.getElementById('userlist').onmouseout = function() { scrollBuddies(false); }
		shadowGadget();
	}
	
	var customPath = System.Gadget.Settings.readString('CustomPath');
	if(customPath != ''){
		purplePath = customPath;
	} else {
		purplePath = System.Environment.getEnvironmentVariable('APPDATA') + "\\.purple";
	}
}

function getMousePosition(event){
	xMousePos = window.event.x;
	yMousePos = window.event.y;
}

function scrollBuddies(start){
	if(start){
		scrollTimer = setInterval('scrollBuddiesLoop()', 25);
	} else {
		clearInterval(scrollTimer);
	}
}

function scrollBuddiesLoop(){
	var hDiff = document.getElementById('userlist').offsetHeight - document.getElementById('buddycontainer').offsetHeight;
	if(hDiff < 0 && scrollPos <= 0 && scrollPos >= hDiff){
		var relPos = yMousePos - document.getElementById('userlist').offsetTop;
		var relCmp = Math.round(document.getElementById('userlist').offsetHeight / 2);
		// split the div into 12 vertical sections, with the middle 6 being no-move zones
		// (makes it easier to select a user if there's a decent area where the mouse won't auto-scroll the list)
		var moveAmt = Math.round((relCmp - relPos) / relCmp * 6);
		if(moveAmt < 0){
			moveAmt = moveAmt + 2 > 0 ? 0 : moveAmt + 2;
		} else if(moveAmt > 0){
			moveAmt = moveAmt - 2 < 0 ? 0 : moveAmt - 2;
		}
		scrollPos = scrollPos + moveAmt;
		if(scrollPos > 0){
			scrollPos = 0;
		} else if(scrollPos < hDiff){
			scrollPos = hDiff;
		}
		document.getElementById('buddycontainer').style.top = scrollPos + 'px';
	}
}

function updateCSS(selector, text, value){
	var cr = document.styleSheets[0].rules;
	for(var i = 0; i < cr.length; i++){
		if(cr[i].selectorText.toLowerCase() == selector){
			if(text){
				if(cr[i].style.color != ''){
					cr[i].style.color = value;
					break;
				}
			} else {
				if(cr[i].style.backgroundColor != ''){
					cr[i].style.backgroundColor = value;
					break;
				}
			}
		}
	}
}
